package top.pengdong.pictureShare.userAuth.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import top.pengdong.pictureShare.common.model.R;
import top.pengdong.pictureShare.common.utils.IPAddress;
import top.pengdong.pictureShare.common.utils.Tool;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @projectName: pictureShare
 * @see: top.pengdong.pictureShare.userAuth.controller
 * @author: pc
 * @createTime: 2022/5/3 15:31
 * @version: 1.0
 */
@RestController
@RequestMapping("api/tool")
public class ToolController {

	//这里输入你申请到的key
	private static final String APP_KEY="XKWBZ-EZW63-ITG35-YHT5B-ONJQE-SYF4G";

	@Autowired
	RestTemplate restTemplate;

	@GetMapping("/get_ip")
	public R get_ip(@RequestParam(value = "ip", required = false) String ip, HttpServletRequest request) {
		if (ip != null) return R.ok("ip属地").put("result", Tool.getAddress(ip));
		String ipAddr = IPAddress.getIpAddr(request);
		Map<String, String> map = new HashMap<>();
		map.put("ip", ipAddr);
		// TODO 这里不知要不要检验ip地址正确性
		map.put("address", Tool.getAddress(ipAddr));
		return R.ok("返回用户地址信息").put("result", map);
	}

	/**
	 * 腾讯云服务获取ip属地
	 * @param ip
	 * @return
	 */
	public String getIpAddr(String ip){
		JSONObject forObject = restTemplate.getForObject("https://apis.map.qq.com/ws/location/v1/ip?ip="+ip+"&key="+APP_KEY,
				JSONObject.class);
		JSONObject location = forObject.getJSONObject("result").getJSONObject("location");
		Object lat = location.get("lat");
		Object lng = location.get("lng");
		String latLng=lat.toString()+","+lng.toString();
		System.out.println("经纬度"+latLng);
		//获取经纬度对应的地址原来的不详细没有给到街道
		JSONObject forObject1 = restTemplate.getForObject("https://apis.map.qq.com/ws/geocoder/v1/?location=" + latLng + "&key=" + APP_KEY, JSONObject.class);
		//位置描述
		Object o = forObject1.getJSONObject("result").get("address");
		return  o.toString();
	}
}
